<template>
  <div class="role">
    <page-search :search-form-config="searchFormConfig"></page-search>
    <page-content
      :content-table-config="contentTableConfig"
      pageName="role"
      @newBtnClick="handleNewBtnClick"
      @editBtnClick="handleEditBtnClick"
    ></page-content>
    <page-modal
      ref="pageModalRef"
      pageName="role"
      :modal-config="modalConfig"
      :default-info="defaultInfo"
      :other-info="otherInfo"
    >
      <div class="menu-tree">
        <el-tree
          ref="elTreeRef"
          :data="menus"
          show-checkbox
          node-key="id"
          :props="{ children: 'children', label: 'name' }"
          @check="handleCheckChange"
        />
      </div>
    </page-modal>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, ref, nextTick } from 'vue'

import { useStore } from '@/store'
import { getMenuLeafKeys } from '@/utils/map-menus'
import { ElTree } from 'element-plus/lib/components'

import PageContent from '@/components/page-content'
import PageSearch from '@/components/page-search'
import PageModal from '@/components/page-modal'

import { contentTableConfig } from './config/content.config'
import { searchFormConfig } from './config/search.config'
import { modalConfig } from './config/modal.config'

import { usePageModal } from '@/hooks/use-page-modal'

export default defineComponent({
  name: 'role',
  components: {
    PageContent,
    PageSearch,
    PageModal
  },
  setup() {
    //处理pageModal的hook
    const elTreeRef = ref<InstanceType<typeof ElTree>>()
    const editCallBack = (item: any) => {
      const leafKets = getMenuLeafKeys(item.menuList)
      nextTick(() => {
        console.log(leafKets)
        elTreeRef.value?.setCheckedKeys(leafKets, false)
      })
    }

    const [handleNewBtnClick, handleEditBtnClick, pageModalRef, defaultInfo] =
      usePageModal(undefined, editCallBack)

    const store = useStore()
    const menus = computed(() => store.state.entireMenu)
    const otherInfo = ref({})

    const handleCheckChange = (data1: any, data2: any) => {
      const checkedKeys = data2.checkedKeys
      const halfCheckedKeys = data2.halfCheckedKeys
      const menuList = { ...checkedKeys, ...halfCheckedKeys }
      console.log(menuList)
      otherInfo.value = { menuList }
    }

    return {
      contentTableConfig,
      searchFormConfig,
      modalConfig,
      handleNewBtnClick,
      handleEditBtnClick,
      pageModalRef,
      defaultInfo,
      menus,
      otherInfo,
      handleCheckChange,
      elTreeRef
    }
  }
})
</script>

<style scoped>
.menu-tree {
  margin-left: 25px;
}
</style>
